package com.neuedu.it.teach.controller;

import com.neuedu.it.teach.controller.vo.Result;
import com.neuedu.it.teach.entity.Help;
import com.neuedu.it.teach.entity.User;
import com.neuedu.it.teach.service.HelpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/help")
public class HelpController {

    @Autowired
    private HelpService helpService;

    // 添加互助信息   已测试达梦
    @PostMapping("/add")
    public Result<String> addHelp(@RequestBody Help help) {
        Help result=helpService.insertHelp(help);
        if(result == null)
        {
            return Result.badRequest("添加失败,请检查数据是否有误！");
        }
        return Result.success("添加成功");
    }

    // 获取所有状态为 pending 的互助信息 已测试达梦
    @GetMapping("/all/pending")
    public Result<List<Map<String, Object>>> getAllPendingHelp() {
        List<Map<String, Object>> pendingHelps = helpService.getAllPendingHelp();

        // 遍历结果集，将CLOB对象转换为字符串
        List<Map<String, Object>> convertedHelps = new ArrayList<>();
        for (Map<String, Object> help : pendingHelps) {
            Map<String, Object> convertedHelp = new HashMap<>();

            // 遍历原始字段名，动态处理大小写
            for (Map.Entry<String, Object> entry : help.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();

                String newKey = key.toLowerCase();

                // 检查字段是否为CLOB类型
                if ("DESCRIPTION".equalsIgnoreCase(key) && value instanceof Clob) {
                    Clob clob = (Clob) value;
                    try {
                        String descriptionStr = clob.getSubString(1, (int) clob.length());
                        convertedHelp.put(newKey, descriptionStr);
                    } catch (SQLException e) {
                        e.printStackTrace();
                        convertedHelp.put(newKey, "Error converting CLOB to string");
                    }
                } else {
                    convertedHelp.put(newKey, value);
                }
            }

            convertedHelps.add(convertedHelp);
        }

        System.out.println(convertedHelps);
        return Result.success(convertedHelps);
    }

    // 根据 help_id 查询互助信息 已测试达梦
// 根据 help_id 查询互助信息
    @GetMapping("/find/{helpId}")
    public Result<Map<String, Object>> getHelpByHelpId(@PathVariable("helpId") Integer helpId) {
        Help help = new Help();
        help.setHelpId(helpId);
        Map<String, Object> result = helpService.queryHelpByHelpId(help);
        if (result == null) {
            return Result.notFound("互助信息未找到");
        }
        return Result.success(result);
    }

    @GetMapping("/find/title")
    public Result<List<Map<String, Object>>> getPendingHelpByTitle(@RequestParam("title") String title) {
        List<Map<String, Object>> result = helpService.getPendingHelpByTitle(title);
        return Result.success(result);
    }


    // 根据 user_id 查询互助信息
    @GetMapping("/find/user")
    public Result<List<Map<String, Object>>> getHelpByUserId(HttpServletRequest request) {
        System.out.println("getHelpByUserId");
        User user = (User) request.getAttribute("user");
        if (user == null) {
            // 如果没有从请求中获取到用户信息，返回错误
            return Result.custom(401, "未授权，用户信息缺失");
        }
        Help help = new Help();
        help.setUserId(user.getId());
        List<Map<String, Object>> result = helpService.queryHelpByUserId(help);
        if (result == null) {
            return Result.notFound("该用户无互助信息");
        }
        return Result.success(result);
    }

    // 删除互助信息 已测试 达梦
    @DeleteMapping("/delete/{helpId}")
    public Result<String> deleteHelp(@PathVariable("helpId") Integer helpId) {
        Help help = new Help();
        help.setHelpId(helpId);
        helpService.deleteHelp(help);
        return Result.success("删除成功");
    }

/*    // 更新互助信息状态 已测试
    @PutMapping("/update/status")
    public Result<String> updateHelpStatus(@RequestBody Help help) {
        helpService.updateHelp(help);
        return Result.success("状态更新成功");
    }*/
}
/*TODO: 完成互助表的增删查改，
   在增加的时候，要写一个随机生成，获得200-500的奖励值。
   查的时候，分几种查，一种是获取全部的，这个要限制求助状态，只有pending的才能返回，还有一个根据help_id返回全部数据。还有一个根据user_id 返回这个人的全部数据
   删除，好像没有，
   改，好像只需要改状态
*  */

/**
 *-- 2. 互助信息表（家长发布），增加奖励字段 reward 和授课相关字段
 DROP TABLE IF EXISTS `mutual_help`;
 CREATE TABLE `mutual_help` (
 `help_id` INT NOT NULL AUTO_INCREMENT,
 `user_id` INT NOT NULL,                        -- 关联家长用户
 `student_id` INT DEFAULT NULL,                 -- 关联学生信息（新增字段）
 `title` VARCHAR(255) NOT NULL,                 -- 求助标题
 `description` TEXT NOT NULL,                   -- 求助内容
 `location` VARCHAR(255) DEFAULT NULL,          -- 位置或区域（可选）
 `status` VARCHAR(50) DEFAULT 'pending',        -- 求助状态（例如 pending, in_progress, completed）
 `reward` DECIMAL(10,2) DEFAULT 0,              -- 求助完成奖励值
 `help_type` VARCHAR(50) DEFAULT 'online',      -- 求助方式：online 或 offline
 `subject` VARCHAR(100) DEFAULT NULL,           -- 求助的科目，例如“数学”
 `frequency` VARCHAR(100) DEFAULT NULL,         -- 授课频率，例如“每周2次”
 `duration` VARCHAR(100) DEFAULT NULL,          -- 单次时长，例如“1.5/2小时等”
 `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`help_id`),
 FOREIGN KEY (`user_id`) REFERENCES `users`(`user_id`) ON DELETE CASCADE,
 FOREIGN KEY (`student_id`) REFERENCES `student_info`(`student_id`) ON DELETE SET NULL
 ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
* */